package cn.time1024.time_app.ui.account

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import cn.time1024.time_app.databinding.FragmentAccountManageBinding
import com.example.timeassistant.network.ApiService
import com.example.timeassistant.network.ResponseEnvelope
import com.example.timeassistant.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AccountManageFragment : Fragment() {

    private var _binding: FragmentAccountManageBinding? = null
    private val binding get() = _binding!!

    private lateinit var adapter: TransactionsAdapter
    private var pageNo = 1
    private var pageSize = 10
    private var isLoading = false
    private var hasMore = true
    private var startDate: String? = null
    private var endDate: String? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentAccountManageBinding.inflate(inflater, container, false)
        setupList()
        setupActions()
        loadPage(true)
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun setupList() {
        adapter = TransactionsAdapter(
            onEdit = { item -> showEditDialog(item) },
            onDelete = { item ->
                val payload = ApiService.TransactionSubmit(transactionId = item.transactionId)
                RetrofitClient.api.deleteTransaction(payload).enqueue(simpleVoidCallback("删除成功", "删除失败"))
            }
        )
        binding.rvTransactions.layoutManager = LinearLayoutManager(requireContext())
        binding.rvTransactions.adapter = adapter
        binding.swipeRefresh.setOnRefreshListener { loadPage(true) }
    }

    private fun setupActions() {
        binding.fabAdd.setOnClickListener { showAddDialog() }
        binding.btnFilter.setOnClickListener {
            startDate = binding.etStart.text?.toString()?.trim().takeIf { !it.isNullOrEmpty() }
            endDate = binding.etEnd.text?.toString()?.trim().takeIf { !it.isNullOrEmpty() }
            pageNo = 1
            loadPage(true)
        }
    }

    private fun loadPage(reset: Boolean) {
        if (isLoading) return
        isLoading = true
        if (reset) { pageNo = 1; hasMore = true }
        RetrofitClient.api.getTransactionsPage(pageNo = pageNo, pageSize = pageSize, startDate = startDate, endDate = endDate)
            .enqueue(object : Callback<ResponseEnvelope<ApiService.PageResult<ApiService.TransactionItem>>> {
                override fun onResponse(call: Call<ResponseEnvelope<ApiService.PageResult<ApiService.TransactionItem>>>, response: Response<ResponseEnvelope<ApiService.PageResult<ApiService.TransactionItem>>>) {
                    isLoading = false
                    binding.swipeRefresh.isRefreshing = false
                    val data = response.body()?.data
                    val list = data?.rows ?: emptyList()
                    val total = data?.totalRows ?: 0
                    binding.tvTotal.text = "共 ${total} 条"
                    if (reset) adapter.replaceAll(list) else adapter.appendAll(list)
                    hasMore = (adapter.itemCount < total)
                    if (hasMore) pageNo += 1
                }
                override fun onFailure(call: Call<ResponseEnvelope<ApiService.PageResult<ApiService.TransactionItem>>>, t: Throwable) {
                    isLoading = false
                    binding.swipeRefresh.isRefreshing = false
                    Toast.makeText(requireContext(), "网络错误：${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
    }

    private fun showAddDialog() {
        val etAmount = EditText(requireContext()).apply { hint = "金额" }
        val spType = android.widget.Spinner(requireContext())
        val types = arrayOf("支出", "收入")
        spType.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, types)
        val etCategory = EditText(requireContext()).apply { hint = "分类" }
        val etDate = EditText(requireContext()).apply { hint = "日期(yyyy-MM-dd)" }
        val etNote = EditText(requireContext()).apply { hint = "备注(可选)" }
        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 16, 32, 0)
            addView(etAmount)
            addView(spType)
            addView(etCategory)
            addView(etDate)
            addView(etNote)
        }
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("新增记录")
            .setView(wrapper)
            .setPositiveButton("确定") { _, _ ->
                val amount = etAmount.text?.toString()?.toDoubleOrNull()
                val type = types[spType.selectedItemPosition]
                val category = etCategory.text?.toString()?.trim()
                val date = etDate.text?.toString()?.trim()
                val note = etNote.text?.toString()?.trim()
                if (amount == null || date.isNullOrEmpty()) {
                    Toast.makeText(requireContext(), "金额与日期不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                val payload = ApiService.TransactionSubmit(amount = amount, type = type, category = category, transactionDate = date, note = note)
                RetrofitClient.api.addTransaction(payload).enqueue(simpleVoidCallback("添加成功", "添加失败"))
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showEditDialog(item: ApiService.TransactionItem) {
        val etAmount = EditText(requireContext()).apply { hint = "金额"; setText(item.amount?.toString() ?: "") }
        val spType = android.widget.Spinner(requireContext())
        val types = arrayOf("支出", "收入")
        spType.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, types)
        spType.setSelection(if ((item.type ?: "支出") == "收入") 1 else 0)
        val etCategory = EditText(requireContext()).apply { hint = "分类"; setText(item.category ?: "") }
        val etDate = EditText(requireContext()).apply { hint = "日期(yyyy-MM-dd)"; setText(item.transactionDate ?: "") }
        val etNote = EditText(requireContext()).apply { hint = "备注(可选)"; setText(item.note ?: "") }
        val wrapper = android.widget.LinearLayout(requireContext()).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(32, 16, 32, 0)
            addView(etAmount)
            addView(spType)
            addView(etCategory)
            addView(etDate)
            addView(etNote)
        }
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("编辑记录")
            .setView(wrapper)
            .setPositiveButton("保存") { _, _ ->
                val amount = etAmount.text?.toString()?.toDoubleOrNull()
                val type = types[spType.selectedItemPosition]
                val category = etCategory.text?.toString()?.trim()
                val date = etDate.text?.toString()?.trim()
                val note = etNote.text?.toString()?.trim()
                if (amount == null || date.isNullOrEmpty()) {
                    Toast.makeText(requireContext(), "金额与日期不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                val payload = ApiService.TransactionSubmit(transactionId = item.transactionId, amount = amount, type = type, category = category, transactionDate = date, note = note)
                RetrofitClient.api.editTransaction(payload).enqueue(simpleVoidCallback("保存成功", "保存失败"))
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun simpleVoidCallback(successMsg: String, failMsg: String): Callback<ResponseEnvelope<Any?>> {
        binding.swipeRefresh.isRefreshing = true
        return object : Callback<ResponseEnvelope<Any?>> {
            override fun onResponse(call: Call<ResponseEnvelope<Any?>>, response: Response<ResponseEnvelope<Any?>>) {
                binding.swipeRefresh.isRefreshing = false
                val body = response.body()
                val ok = (body?.success == true) || (body?.code == "00000")
                if (response.isSuccessful && ok) {
                    Toast.makeText(requireContext(), successMsg, Toast.LENGTH_SHORT).show()
                    loadPage(true)
                } else {
                    Toast.makeText(requireContext(), body?.message ?: failMsg, Toast.LENGTH_SHORT).show()
                }
            }
            override fun onFailure(call: Call<ResponseEnvelope<Any?>>, t: Throwable) {
                binding.swipeRefresh.isRefreshing = false
                Toast.makeText(requireContext(), "$failMsg：${t.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

